﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCacheDClient.Exceptions;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using NCacheDClient.Internal;
using System.Globalization;

namespace NCacheDClient
{
    public static class NCacheD
    {

        private static NCacheDServerStore factory = new NCacheDServerStore();

        public static T Get<T>(string key)
        {
            byte[] buffer = null;

            var client = factory.GetServerByKey(key);

            
            buffer = client.Get(key);
            

            if (buffer == null || buffer.Length == 0)
                return default(T);

            object valueFromCache;
            using (var memStream = new MemoryStream(buffer))
            {
                var formatter = new BinaryFormatter();

                valueFromCache = formatter.Deserialize(memStream);
            }

            if (!(valueFromCache is T))
            {
                var errorMessage = string.Format(CultureInfo.InvariantCulture, "Value in cache is type '{0}'. You requested type '{1}'.", valueFromCache.GetType(), typeof(T));
                throw new InvalidCastException(errorMessage);
            }
            else
            {
                return (T)valueFromCache;
            }
        }


        public static void Put(string key, DateTime expiration, object value)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            var client = factory.GetServerByKey(key);

            using (var memStream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(memStream, value);

                var buffer = memStream.ToArray();

                client.Put(key, expiration, buffer);
            }
        }

        public static void Delete(string key)
        {
            var client = factory.GetServerByKey(key);
            client.Delete(key);
        }

    }
}
